﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp_MvvmWindowBus.Base;

public class WindowProvider
{
    public static Dictionary<string, WindowProvideInfo> dicTypes = new Dictionary<string, WindowProvideInfo>();

    public static Window? subMainWindow = null;

    /// <summary>
    /// 注册窗体对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="windowName"></param>
    public static void Register<T>(string windowName = "", Window? oner = null)
    {
        if (string.IsNullOrEmpty(windowName))
            windowName = typeof(T).Name;
        if (!dicTypes.ContainsKey(windowName))
            dicTypes.Add(windowName, new WindowProvideInfo()
            {
                WindowType = typeof(T),
                Ower = oner
            });
    }

    public static bool ShowDialog(string windowName, object dataContext)
    {
        if (string.IsNullOrEmpty(windowName))
            throw new ArgumentException("windowName不能为空！");

        if (!dicTypes.ContainsKey(windowName))
            throw new Exception("未找到窗体对象！");

        if (!dicTypes.TryGetValue(windowName, out var dialog))
            throw new Exception("未找到窗体对象！");

        subMainWindow = (Window)Activator.CreateInstance(dialog.WindowType)!;
        if (dialog != null)
            subMainWindow.Owner = dialog.Ower;
        subMainWindow.DataContext = dataContext;
        return subMainWindow!.ShowDialog() == true;

    }

    public static void AcceptWindow(string windowName)
    {
        if (string.IsNullOrEmpty(windowName))
            throw new ArgumentException("windowName不能为空！");

        if (!dicTypes.ContainsKey(windowName))
            throw new Exception("未找到窗体对象！");

        if (!dicTypes.TryGetValue(windowName, out var dialog))
            throw new Exception("未找到窗体对象！");

        if(subMainWindow!=null)
            subMainWindow.DialogResult = true;
    }
}

public class WindowProvideInfo
{
    public Type WindowType { get; set; }
    public Window? Ower { get; set; }
}


